import Vue from "vue";
import axios from "axios";
import { Message } from "element-ui";
// import Qs from "querystring";
// import QS from 'qs';
import vm from "@/main.js";

let loading;
axios.defaults.withCredentials = true;
// 创建axios实例
const service = axios.create({
	baseURL: "/",
	timeout: 30000,
	headers: {
		"Content-Type": "application/json",
	},
});

// request拦截器
service.interceptors.request.use(
	config => {
		loading = Vue.prototype.$loading({
			lock: true,
			text: "Loading",
			spinner: "el-icon-loading",
			background: "rgba(0, 0, 0, 0.7)",
		});
		if (localStorage.token && localStorage.userId) {
			config.headers["token"] = `${localStorage.token}`;
			config.headers["userId"] = `${localStorage.userId}`;
		}
		if (config.method === "post") {
			config.data = JSON.stringify({
				...config.data,
			});
		}

		return config;
	},
	error => {
		Promise.reject(error);
	}
);

// response拦截器
let num = 0;
service.interceptors.response.use(
	response => {
		const res = response.data;
		if (res.code === 1) {
			//正常
			loading.close();
			return res;
		} else if (res.code === 200) {
			loading.close();
			return res;
		} else if (res.code === 500) {
			loading.close();
			Message({
				message: res.message,
				showClose: true,
				type: "error",
				duration: 10 * 1000,
			});
			return res;
		} else if (res.code === 998) {
			num++;
			loading.close();
			if (num === 1) {
				Message({
					message: res.message,
					showClose: true,
					type: "warning",
					duration: 10 * 1000,
				});
			}
			localStorage.clear();
			vm.$router.push("/");
			return res;
		} else if (res.code === 999) {
			loading.close();
			Message({
				message: "请登录",
				type: "warning",
				duration: 3 * 1000,
			});
			localStorage.clear();
			vm.$router.push("/");
			return res;
		} else {
			loading.close();
			Message({
				message: "连接超时",
				showClose: true,
				type: "error",
				duration: 3 * 1000,
			});
			// return Promise.reject(new Error((res && res.msg) ? res.msg : 'Error'));
			return Promise.reject(res);
		}
	},
	error => {
		loading.close();
		Message({
			message: "服务器异常",
			type: "error",
			showClose: true,
			duration: 3 * 1000,
		});
		return Promise.reject(error);
	}
);
// 用于文件上传（不需要Qs.stringify,直接添加form-data就行）
const filereq = axios.create({
	baseURL: "/",
	timeout: 30000,
	headers: {
		"Content-Type": "multipart/form-data",
	},
});

// request拦截器
filereq.interceptors.request.use(
	config => {
		loading = Vue.prototype.$loading({
			lock: true,
			text: "Loading",
			spinner: "el-icon-loading",
			background: "rgba(0, 0, 0, 0.7)",
		});
		// const UserId = localStorage.getItem('UserId');
		// if (UserId) {
		//   config.headers.common.UserId = UserId;
		// }
		return config;
	},
	error => {
		loading.close();
		Promise.reject(error);
	}
);

// response拦截器
filereq.interceptors.response.use(
	response => {
		const res = response.data;
		if (res.code == 999) {
			loading.close();
			Message({
				message: "请登录",
				type: "info",
				duration: 3 * 1000,
			});
			vm.$router.push("/");
			return res;
		}
		if (res.code !== 0) {
			loading.close();
			Message({
				message: res.msg,
				type: "error",
				showClose: true,
				duration: 10 * 1000,
			});
			// return Promise.reject(new Error((res && res.msg) ? res.msg : 'Error'));
			return Promise.reject(res);
		} else {
			loading.close();
			return res;
		}
	},
	error => {
		loading.close();
		Message({
			message: error.message,
			type: "error",
			showClose: true,
			duration: 3 * 1000,
		});
		return Promise.reject(error);
	}
);

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
	return new Promise((resolve, reject) => {
		service
			.get(url, {
				params: params,
			})
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data);
			});
	});
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]   QS.stringify(params)
 */
export function post(url, params) {
	return new Promise((resolve, reject) => {
		service
			.post(url, params)
			.then(res => {
				resolve(res.data);
			})
			.catch(err => {
				reject(err.data);
			});
	});
}

export { service, filereq };
